package com.jz.community.moduleshoppingguide.search.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.bean.baseGoods.BaseGoodsInfo;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.search.adapter.SearchGoodsListAdapter;
import com.jz.community.moduleshoppingguide.search.task.SearchGoodsListTask;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by Tony.Fan on 2018/6/4 09:33
 * <p>
 * 搜索商品
 */
public class GoodsListFragment extends BaseMvpFragment implements OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R2.id.sr_comprehensive_btn)
    TextView srComprehensiveBtn;
    @BindView(R2.id.sr_price_tv)
    TextView srPriceTv;
    @BindView(R2.id.sr_price_iv)
    ImageView srPriceIv;
    @BindView(R2.id.sr_price_btn)
    LinearLayout srPriceBtn;
    @BindView(R2.id.fragment_search_parent)
    LinearLayout fragmentSearchParent;
    @BindView(R2.id.search_change_btn)
    Button searchChangeBtn;
    @BindView(R2.id.sr_rv)
    RecyclerView srRv;
    @BindView(R2.id.sr_refresh)
    SmartRefreshLayout srRefresh;

    private GridLayoutManager gridLayoutManager;
    private SearchGoodsListAdapter searchGoodsListAdapter;
    private int viTag = 0;
    private int sort; //价格排序
    private LoadService loadService;
    private String keyWord;
    private int page = 0;
    private BaseGoodsInfo baseGoodsInfo;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shoppingguide_fragment_sr_normal;
    }

    @Override
    protected void initView() {
        super.initView();
        srComprehensiveBtn.setEnabled(false);
        searchChangeBtn.setSelected(true);
    }

    public void setKeyWord(String searchKeyWord) {
        keyWord = searchKeyWord;
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        loadService = LoadSir.getDefault().register(fragmentSearchParent);
        loadService.setCallBack(EmptyCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                ImageView empty_iv = view.findViewById(R.id.empty_img);
                TextView empty_tv = view.findViewById(R.id.empty_tv);
                empty_iv.setImageResource(R.mipmap.empty_default);
                empty_tv.setText("未找到相关搜索结果，换个词试试！");
            }
        });
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        getSearchGoodsList(true);
    }

    @Override
    public void onLoadMoreRequested() {
        getSearchGoodsList(false);
    }


    private void getSearchGoodsList(boolean isRefresh) {
        new SearchGoodsListTask(getActivity(), new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                baseGoodsInfo = (BaseGoodsInfo) o;
                if (!Preconditions.isNullOrEmpty(baseGoodsInfo) && !Preconditions.isNullOrEmpty(baseGoodsInfo.get_embedded().getContent())) {
                    srRefresh.finishRefresh();
                    loadService.showSuccess();
                    handleSearchListAdapter(baseGoodsInfo.get_embedded(), isRefresh);
                } else {
                    loadService.showCallback(EmptyCallback.class);
                }
            }
        }).execute(keyWord, ConverterUtils.toString(sort), page + "");
    }

    public void changeSearch(String content) {
        page = 0;
        keyWord = content;
        if (null != searchGoodsListAdapter) {
            searchGoodsListAdapter.replaceData(new ArrayList<>());
        }
        getSearchGoodsList(true);
    }

    /**
     * 绑定数据
     *
     * @param embeddedInfo
     */
    private void handleSearchListAdapter(BaseGoodsInfo.EmbeddedBeanXX embeddedInfo, boolean isRefresh) {

        page++;

        if (searchGoodsListAdapter == null || isRefresh) {
            gridLayoutManager = new GridLayoutManager(getActivity(), 2);
            srRefresh.setOnRefreshListener(this);
            srRv.setHasFixedSize(true);
            srRv.setFocusable(false);
            srRv.setLayoutManager(gridLayoutManager);
            searchGoodsListAdapter = new SearchGoodsListAdapter(R.layout.module_shoppingguide_item_farmer_grid, embeddedInfo.getContent(), gridLayoutManager);
            searchGoodsListAdapter.setEnableLoadMore(false);
            searchGoodsListAdapter.setOnLoadMoreListener(this, srRv);
            searchGoodsListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
            searchGoodsListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    RouterCommonUtils.startParameterActivity(RouterIntentConstant.MODULE_SHOPPING_GOODS_DETAIL, "url", searchGoodsListAdapter.getData().get(position).get_links().getSelf().getHref());
                }
            });
            srRv.setAdapter(searchGoodsListAdapter);
        } else {
            searchGoodsListAdapter.addData(embeddedInfo.getContent());
        }

        if (baseGoodsInfo.getPage().getTotalPages() <= page) {
            searchGoodsListAdapter.loadMoreEnd();
        } else {
            searchGoodsListAdapter.loadMoreComplete();
        }
    }

    private void setGridLayoutManagerCount(int count) {
        if (!Preconditions.isNullOrEmpty(gridLayoutManager)) {
            gridLayoutManager.setSpanCount(count);
            searchGoodsListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void addListener() {
        super.addListener();
        searchChangeBtn.setOnClickListener(v -> {
            if (searchChangeBtn.isSelected()) {
                searchChangeBtn.setSelected(false);
                setGridLayoutManagerCount(1);
            } else {
                searchChangeBtn.setSelected(true);
                setGridLayoutManagerCount(2);
            }
        });

        srComprehensiveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                srComprehensiveBtn.setEnabled(false);
                srComprehensiveBtn.setTextColor(getResources().getColor(R.color.home_red));
                srPriceTv.setTextColor(getResources().getColor(R.color.font_gary));
                srPriceIv.setImageResource(R.mipmap.sr_normal);
                page = 0;
                getSearchGoodsList(true);
            }
        });

        srPriceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                srComprehensiveBtn.setEnabled(true);
                srComprehensiveBtn.setTextColor(getResources().getColor(R.color.font_gary));
                srPriceTv.setTextColor(getResources().getColor(R.color.home_red));
                page = 0;
                if (viTag % 2 == 0) {
                    srPriceIv.setImageResource(R.mipmap.sr_up);
                    viTag++;
                    sort = 0;
                } else {
                    viTag = 0;
                    srPriceIv.setImageResource(R.mipmap.sr_down);
                    sort = 1;
                }
                getSearchGoodsList(true);
            }
        });
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        page = 0;
        getSearchGoodsList(true);
    }
}
